package com.kalix.mplive.answeringQuestion.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kalix.framework.core.api.persistence.JsonData;
import com.kalix.framework.core.api.persistence.JsonStatus;
import com.kalix.framework.core.impl.biz.ShiroGenericBizServiceImpl;
import com.kalix.mplive.answeringQuestion.api.biz.IMessageBeanService;
import com.kalix.mplive.answeringQuestion.api.biz.IMessageReplyBeanService;
import com.kalix.mplive.answeringQuestion.api.dao.IMessageBeanDao;
import com.kalix.mplive.answeringQuestion.api.dto.MessageBeanDTO;
import com.kalix.mplive.answeringQuestion.api.dto.MessageDTO;
import com.kalix.mplive.answeringQuestion.api.dto.MessageJsonBeanDTO;
import com.kalix.mplive.answeringQuestion.entities.MessageBean;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 功能描述：maven包引用  install wrap:mvn:com.alibaba/fastjson/1.2.47
 *
 * @Author: Wanghw
 * @Date: 2019/11/23
 * @Version V1.0
 *
**/

/**
 * 功能描述:
 *
 * @Description: 论坛实现类
 * @Author: whw
 * @CreateDate: 2019/10/23$ 16:39$
 * @Version:
 */
public class MessageBeanServiceImpl extends ShiroGenericBizServiceImpl<IMessageBeanDao, MessageBean> implements IMessageBeanService {
    private IMessageReplyBeanService iMessageReplyBeanService;
    // 查询留言
    @Override
    public JsonData getMessage() {
//        String sql = "Select m.id,u.name as userName,u.icon,m.messageContent,m.creationDate from mplive_Message m,sys_user u where m.uid = u.id  order by m.creationDate desc";
        String sql ="select m.id,u.name as userName,u.icon,m.photo,m.messageTitle,m.messageContent,m.messageDateTime,m.messageFlag,m.messageJingFlag,COUNT(r.messageid) as counts from mplive_Message m LEFT JOIN sys_user u ON m.uid = u.id LEFT JOIN mplive_messagereply r ON r.messageid = m.id and r.parentid =- 1 GROUP BY m.id,u.name,u.icon ORDER BY m.messageFlag DESC,m.messageJingFlag DESC,m.messageDateTime DESC";
        List<MessageDTO> list = dao.findByNativeSql(sql, MessageDTO.class);
        JsonData jsonData = new JsonData();
        jsonData.setData(list);
        jsonData.setTotalCount((long) list.size());
        return jsonData;
    }
    // 回复管理左侧菜单
    @Override
    public JsonData getMessageReplyForTree() {
        List<MessageJsonBeanDTO> list = new ArrayList<>();
        List<MessageBean> modelList = dao.find("select f from MessageBean f order by f.id desc");
        if (modelList.size() > 0) {
            for (MessageBean messageBean : modelList) {
//                System.out.println(messageBean.getUserName());
                MessageJsonBeanDTO messageJsonBean = new MessageJsonBeanDTO();
                messageJsonBean.setValue(messageBean.getId());
                messageJsonBean.setLabel(messageBean.getMessageContent());
                messageJsonBean.setReplyMessage(messageBean.getMessageContent());
                messageJsonBean.setUserName(messageBean.getUserName());
                messageJsonBean.setReplyNum(messageBean.getReplynum());
                messageJsonBean.setUid(messageBean.getUid());
                list.add(messageJsonBean);
            }
        }
        JsonData jsonData = new JsonData();
        jsonData.setData(list);
        jsonData.setTotalCount((long) list.size());
        return jsonData;
    }

    @Override
    public void deleteAllById(long id) {
        dao.remove(id);
        iMessageReplyBeanService.deleteAllByPostid(id);
    }
    //   新增留言(帖子)

    @Override
    public JsonStatus addMessage(Integer uid,String messageContent,String messageTitle,String photo,String file,String headportrait,String identity) {
        MessageBean messageBean1 =new MessageBean();
        messageBean1.setUid(0);
        messageBean1.setUserName("管理员");
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = df.format(t);
        try {
            messageBean1.setMessageDateTime(df.parse(dateString));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = new JSONObject();
        messageBean1.setMessageTitle(messageTitle);
        messageBean1.setMessageContent(messageContent);
        messageBean1.setMessageFlag(false);
        messageBean1.setMessageJingFlag(false);
        messageBean1.setPhoto(photo);
        messageBean1.setUid(uid);
        messageBean1.setFile(file);
        messageBean1.setHeadportrait(headportrait);
        messageBean1.setIdentity(identity);
        messageBean1.setFraction(0L);
        messageBean1.setNumber(0L);
        messageBean1.setBrowsenum(0L);
        messageBean1.setReplynum(0L);
        messageBean1.setScoreArray(jsonObject.toString());
        MessageBean messageBean2 = dao.save(messageBean1);
        JsonStatus jsonS = new JsonStatus();
        if (messageBean2 != null) {
            jsonS.setSuccess(true);
            jsonS.setMsg("保存成功！");
        } else {
            jsonS.setFailure(true);
            jsonS.setMsg("保存失败！");
        }
        return jsonS;
    }

    /**
     * 投票
     * @param id
     * @param fraction
     * @return
     */
    @Override
    public String getFraction(long id,long fraction) {
        Long fractions= 0L;
        Long number= 0L;
        List<MessageBean> modelList = dao.findByNativeSql("select * from mplive_Message  where id="+id , MessageBean.class);
        for (MessageBean list:modelList) {
            fractions=list.getFraction();
            number=list.getNumber();
        }
        fraction += fractions;
        number += 1;
        String sql = "UPDATE mplive_Message SET fraction = "+fraction+", number = "+number+" WHERE id = "+id+"";
        dao.updateNativeQuery(sql);
        Double score = Double.valueOf(fraction/number);
        String sql2 = "UPDATE mplive_Message SET scoreArray = "+score+"  WHERE id = "+id+"";
        dao.updateNativeQuery(sql2);
        return "评分成功";
    }

    /**
     * 根据id查询个人发帖信息
     * @param
     * @return
     */
    @Override
    public JsonData getAddMessage(Integer uid,Integer num){
        int max = num*8;
        int min = (num-1)*8;
        String sql = "SELECT M . ID, M .headportrait, M .messageflag, M .messagejingflag, M .messagetitle," +
                "u. NAME AS userName,M .messagedatetime,M .browsenum,M .replynum" +
                " FROM mplive_message M,sys_user u" +
                " WHERE M .uid = '"+uid+"' AND M .uid = u. ID" +
                " ORDER BY" +
                " messageDateTime DESC" +
                " limit 8 offset "+ min;
        List<MessageBean> modelList = dao.findByNativeSql(sql ,MessageBean.class);
        JsonData jsonData = new JsonData();
        jsonData.setData(modelList);
        List<Integer> count = dao.findByNativeSql("select count(*) from mplive_message  where uid='"+uid+"'",Integer.class);
        if(count.size()>0){
            jsonData.setTotalCount((long)count.get(0));
        }
        return jsonData;
    }

    /**
     * 浏览人数
     * @param id
     * @return
     */
    @Override
    public String getbrowsenum(long id) {
        Long browsenum = 0L;
        List<MessageBean> modelList = dao.findByNativeSql("select * from mplive_message * where id="+id , MessageBean.class);
        for (MessageBean list:modelList) {
            browsenum=list.getBrowsenum();
        }
         browsenum+= 1L;
        String sql = "UPDATE mplive_Message SET  browsenum = "+browsenum+" WHERE id = "+id+"";
        dao.updateNativeQuery(sql);
        return "浏览+1";
    }

    /**
     * 评论人数
     * @param id
     * @return
     */
    @Override
    public String getreplynum(long id) {
        Long replynum = 0L;
        List<MessageBean> modelList = dao.findByNativeSql("select * from mplive_message * where id="+id ,MessageBean.class);
        for (MessageBean list:modelList) {
            replynum=list.getReplynum();
        }
        replynum+= 1L;
        String sql = "UPDATE mplive_Message SET  replynum = "+replynum+" WHERE id = "+id+"";
        dao.updateNativeQuery(sql);
        return "评论+1";
    }

    /**
     * 是否投票
     * @param id
     * @return
     */
    @Override
    public String getwhethertovote(long id) {
        String sql = "UPDATE mplive_Message SET  whethertovote = "+true+" WHERE id = "+id+"";
        dao.find(sql);
        return "已经投票";
    }

    /**
     * 查询共有多少条帖子数据
     * @return
     */
    @Override
    public JsonData getsum() {
        String sql = "SELECT count (m.messageTitle) FROM MessageBean m";
//        System.out.println(dao.findByNativeSql(sql,MessageBean.class));
        List<MessageBean> list = dao.find(sql);
        JsonData jsonData = new JsonData();
        jsonData.setData(list);
        jsonData.setTotalCount((long) list.size());
        return jsonData;
    }

    /**
     * 分页
     * @param num
     * @return
     */
    @Override
    public JsonData getPostinglist(int num) {
        int max = num * 8;
        int min = (num-1)* 8;
        List<Integer> listCount = dao.findByNativeSql("select count(id) from mplive_Message M",Integer.class);
        if(max>listCount.get(0)){
            max = listCount.get(0);
        }
        String sql = "SELECT m.id,m.uid,m.messageContent,m.messageDateTime,m.messageFlag,m.messageJingFlag,m.messageTitle,m.photo,m.fraction,m.number," +
                "m.file,m.browsenum,m.replynum,m.whethertovote,m.headportrait,m.identity,m.scoreArray,u.icon,u.name as userName FROM" +
                " mplive_Message M,sys_user u where M .uid = u. ID ORDER BY" +
                " case when m.messageflag = true and m.messagejingflag = true then 1" +
                " when m.messageflag = true and m.messagejingflag = false then 2" +
                " when m.messageflag = false and m.messagejingflag = true then 3" +
                " when m.messageflag = false and m.messagejingflag = false then 4 end,m.messagedatetime desc" +
                " limit 8 offset "+min;
        List<MessageBeanDTO> list = dao.findByNativeSql(sql,MessageBeanDTO.class);
        JsonData jsonData = new JsonData();
        jsonData.setData(list);
        jsonData.setTotalCount((long) listCount.get(0));
        return jsonData;
        }
    /**
     * 功能描述：根据帖子ID查询详细内容
     *
     * @Author: Wanghw
     * @Date: 2019/11/11
     * @Version V1.0
     *
    **/
    @Override
    public JsonData getForumdetails(Long id) {
        String sql = "SELECT M . ID, M .headportrait, M .messageflag, M .messagejingflag, M .messagetitle," +
                "u. NAME AS userName,M .messagedatetime,M .browsenum,M .replynum,M.identity,M.messageContent,M.uid,M.photo,M.scoreArray,M.file" +
                " FROM mplive_message M,sys_user u" +
                " WHERE M .id = '"+id+"' AND M .uid = u. ID";
        List<MessageBean> list = dao.findByNativeSql(sql,MessageBean.class);
        JsonData jsonData = new JsonData();
        jsonData.setData(list);
        jsonData.setTotalCount((long) list.size());
        return jsonData;
    }

    public IMessageReplyBeanService getiMessageReplyBeanService() {
        return iMessageReplyBeanService;
    }

    public void setiMessageReplyBeanService(IMessageReplyBeanService iMessageReplyBeanService) {
        this.iMessageReplyBeanService = iMessageReplyBeanService;
    }


}
